package com.yc.navy.dayfresh.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.navy.dayfresh.entity.Fav;
import com.yc.navy.dayfresh.entity.Tag;
import com.yc.navy.dayfresh.entity.TagFav;
import com.yc.navy.dayfresh.mapper.FavMapper;
import com.yc.navy.dayfresh.mapper.TagFavMapper;
import com.yc.navy.dayfresh.mapper.TagMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author navy
 * @company 源辰信息
 * @date 2024/9/9
 * @email haijunzhou@hnit.edu.cn
 */
@Service
public class FavBiz {
    @Autowired
    FavMapper favMapper;
    @Autowired
    TagMapper tagMapper;
    @Autowired
    TagFavMapper tagFavMapper;

    @Transactional(rollbackFor = BizException.class)
    public void add(Fav fav) throws BizException {

        // 验证用户输入
        if(fav.getName() == null || fav.getName().isBlank()){
            throw new BizException("请输入链接名称", -1);
        }

        if(fav.getAddr() == null || fav.getAddr().isBlank()){
            throw new BizException("请输入链接地址", -2);
        }

        // TODO 请扩展实现其他字段的验证

        // 保存链接记录
        favMapper.insert(fav);

        // 添加分类(如果分类已经存在,则不添加)
        if(fav.getTags()==null || fav.getTags().isBlank()){
            return;
        }

        String[] tags = fav.getTags().split("[,;，；]+");
        for (String tag : tags) {
            if(tag.isBlank())continue;
            // 查询tag
            // 条件构建器
            LambdaQueryWrapper<Tag> lqw = new LambdaQueryWrapper<Tag>();
            lqw.eq(Tag::getName, tag);
            lqw.eq(Tag::getUid, fav.getUid());
            Tag t = tagMapper.selectOne(lqw);
            if(t == null){
                // 新增分类记录
                t = new Tag();
                t.setName(tag);
                t.setUid(fav.getUid());
                // mybatis plus 会自动返回新增的 id
                tagMapper.insert(t);
            }

            // 添加连接与分类关系记录
            TagFav tf = new TagFav();
            tf.setFid(fav.getId());
            tf.setTid(t.getId());
            tagFavMapper.insert(tf);
        }
    }

    // 1. 在某个分类中置顶, 2. 所有分类中置顶
    public void toTop(Fav fav){
        // 查询链接所在所有分类的所有的链接, 取最小id
        int minSort = favMapper.selectMinSort(fav.getId());
        fav.setSort(minSort);
        favMapper.updateById(fav);
    }

    // 1. 服务启动将链接保存到redis
    @Autowired
    RedisTemplate redisTemplate;
    @PostConstruct
    public void init(){
        // 删除原有数据
        redisTemplate.delete("fav_opens");
        HashOperations hash = redisTemplate.opsForHash();
        // 导入新数据
        favMapper.selectList(null).forEach(f->{
            hash.put("fav_opens",
                    f.getId(),
                    f.getOpens() == null? 0: f.getOpens());
        });
    }

    // 删除网站
    @Transactional
    public void delete(Fav fav){
        favMapper.deleteById(fav);

        List<Integer> tids = tagFavMapper.selectTidByFid(fav.getId());
        for(int tid : tids){
            List<TagFav> t = tagFavMapper.selectTagFavByFid(tid, fav.getId());
            System.out.println("===========" + t);
            if(t == null || t.isEmpty()){
                // 删除tid对应的tag
                tagMapper.deleteById(tid);
            }
        }
        // 删除tag_fav中fid对应的记录
        tagFavMapper.deleteTagFav(fav.getId());
    }

    public List<Fav> toFind(int uid,String name) {
        return favMapper.toFind(uid,name);
    }

}
